package com.blue.gateway.jwt;

import com.blue.gateway.bean.constants.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;

import static com.blue.gateway.bean.constants.JwtConfig.REDIS_USER_PRI_KEY;
import static com.blue.gateway.bean.constants.JwtConfig.REDIS_USER_PUB_KEY;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Configuration
public class JwtRsaKeyAutoConfig implements CommandLineRunner {

    public JwtRsaKeyAutoConfig(){
        log.info("==========初始化JWT核心配置==========");
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private  RsaKeyConfig rsaKeyConfig;

    @Bean
    @ConditionalOnMissingBean(JwtTokenUtil.class)
    public JwtTokenUtil jwtTokenUtil(RsaKeyConfig rsaKeyConfig) {
        return new JwtTokenUtil(rsaKeyConfig);
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("初始化jwt公私密钥....");
        boolean rsaKeyExisted = redisTemplate.hasKey(REDIS_USER_PRI_KEY) && redisTemplate.hasKey(REDIS_USER_PUB_KEY);
        if (rsaKeyExisted) {
            log.info("Redis已有密钥数据，直接设置该服务的配置对象的公钥、私钥信息");
            rsaKeyConfig.setPrivateKey(RsaKeyUtil.toBytes(redisTemplate.opsForValue().get(REDIS_USER_PRI_KEY)));
            rsaKeyConfig.setPublicKey(RsaKeyUtil.toBytes(redisTemplate.opsForValue().get(REDIS_USER_PUB_KEY)));
            return;
        }
        log.info("Redis无密钥数据，直接生成并存储到redis，设置该服务配置对象的公钥、私钥信息");
        Map<String, byte[]> keyMap = RsaKeyUtil.generateKey(JwtConfig.rsaSalt);
        rsaKeyConfig.setPrivateKey(keyMap.get("pri"));
        rsaKeyConfig.setPublicKey(keyMap.get("pub"));
        redisTemplate.opsForValue().set(REDIS_USER_PRI_KEY, RsaKeyUtil.toHexString(keyMap.get("pri")));
        redisTemplate.opsForValue().set(REDIS_USER_PUB_KEY, RsaKeyUtil.toHexString(keyMap.get("pub")));
    }
}
